<!DOCTYPE html>
<html lang="zh">
<head>
    <meta charset="UTF-8">
    <title>文件上传</title>
    <meta name="viewport" content="width=device-width, initial-scale=1.0, minimum-scale=1.0, maximum-scale=1.0, user-scalable=yes">
    <script type="text/javascript" src="jamjs/jquery-1.11.0.js"></script>
    <link rel="stylesheet" type="text/css" href="jamcss/JamTools.css">
    <style type="text/css">

            * {

                margin: 0;

                padding: 0;

            }




            .filename {

                width: 200px;

                text-align: center;

            }



            .filestatus {

                width: auto;

                text-align: center;

            }



            .fileprogress {

                text-align: center;

            }



            .domprogress {

                width: auto;
                min-width: 70%;

            }



            .domsize {

                display: block;

            }



            #tdmsg {

                text-align: center;

            }



            #fileselect {

                display: none;

            }



            span.domtime {

                display:block;

            }


        </style>
  </head>

  <body>
        <div class="container" >
            <input type="button" class="back" id="back"  value="<返回" />
            <h2 id="uploadheader" >上传到:/</h2>
            <input type="file" name="fileselect" id="fileselect" value="" multiple/>
            <input type="button" id="btnselect" value="+添加文件" />
            <input type="button" id="btnupload" style="background-color: green" value="开始上传 ▷" />
            <input type="button" id="pauseupload" style="background-color: darkkhaki" value="暂停 ||" />
            <input type="button" id="stopupload" style="background-color: darkred" value="中止 ▢" />
        </div>
        <hr>
        <table  id="filelist">
            <tr>
                <td class="filename" style="width: 30%;">文件名</td>

                <td class="fileprogress" style="width: 50%;">进度</td>

                <td class="filestatus" style="width: 10%;min-width: 10%;">状态</td>
            </tr>
            <!--<tr><td>人民的名义.avi </td><td><progress value="10" max="100" class="domprogress"></progress><span class="dompercent">10%</span><span class="domsize">0/1.86GB</span></td><td class="filestatus"><span class="domstatus">排队中</span></td></tr>-->
            <tr id="trmsg">
                <td colspan="3" id="tdmsg">请选择要上传的文件!</td>
            </tr>
        </table>
        <hr>

<div id="footer" >
        <p>Posted By: <a href="https://github.com/fandesfyf/JamTools">JamTools</a> | Contact Information: <a href="mailto:fandesfyf@qq.com">fandesfyf@qq.com</a>.</p></div>

<!--   <input type="file" id="file" name="myfile" onchange="onchanges()" multiple="multiple"/>-->
<!--<input type="button" onclick="SerialUploadFile()" value="上传"/>-->
<!--        <script src="jamjs/spark-md5.js" type="text/javascript" charset="utf-8"></script>-->
  <script>
      const filelist = [];//存储上传对象的数组
      var onupload=0;//上传控制变量
      var element = document.getElementById("uploadheader");
        element.innerHTML = "上传到:"+decodeURI(window.location.pathname.replace("jamupload.html",""));
      $("#btnselect").click(function() {

                $("#fileselect").click();

            });

      $("#fileselect").change(function() {

        var files = this.files;
        console.log(files)
        if(files.length > 0) {

            $("#trmsg").remove();

            $(files).each(function(index, item) {
                if (!nameinitems(item.name)){
                    console.log(index, item);
                    filelist.push(item)

                    var filesize = 0;

                    if((item.size / 1024 / 1024 / 1024) >= 1) {

                        filesize = (item.size / 1024 / 1024 / 1024).toFixed(2) + "GB"; // b=>kb=>mb=>gb

                    } else if((item.size / 1024 / 1024 / 1024) < 1 && (item.size / 1024 / 1024) >= 1) {

                        filesize = (item.size / 1024 / 1024).toFixed(2) + "MB";

                    } else if((item.size / 1024 / 1024) < 1 && (item.size / 1024) >= 1) {

                        filesize = (item.size / 1024).toFixed(2) + "KB";

                    } else {

                        filesize = item.size + "B";

                    }

                    var htmlstr = '<tr><td  >' + item.name + '</td><td ><progress value="0" max="100" class="domprogress"></progress><span class="dompercent"> 0/'+filesize+'</span><span class="domtime">等待开始...</span></td><td class="filestatus" ><span class="domstatus">等待中</span></td></tr>';

                    $("#filelist").append(htmlstr);
                }
            });

            console.log(filelist)
            }
            function nameinitems(name){
                var inname =false ;
                for(i=0;i<filelist.length;i++){
                    if (name===filelist[i].name){
                        console.log("in     name")
                        inname=true;
                        break
                    }
                }
                return inname
            }
            });

      $("#pauseupload").click(function (){
          onupload=1;
          console.log("onpause")
      });

      $("#stopupload").click(function (){
          onupload=2;
          console.log("onstop")
      });
      $("#btnupload").click(function() {
        // var files = $("#fileselect")[0].files;
        // $(files).each(function (index, item) {
        //     filelist.push(item)
        //     });
        console.log(filelist);
        $(filelist).each(function (index,item){
            var file = filelist[index];
            console.log("开始上传:",file.name,file["success"])
            if (file["success"] === undefined ){
                try{
                jamfileupload(filelist[index], $("span.domstatus").eq(index), $("span.dompercent").eq(index), $(".domprogress").eq(index), $("span.domtime").eq(index));
            }catch (e) {
                    console.log(e)
                }
            }
            else {
                console.log("已上传过!")
            }
        });

        });

      $("#back").click(function (){
          loc=window.location.pathname.replace("jamupload.html","");
          if (loc==="/"){
              loc="/home"
          }
          window.location=loc;
      });
      //文件上传

       function jamfileupload(file, dommsg, dompercentmb, domprogress, domtime, fn) {
                var filename=file.name;
                var startTime = new Date();
                var repeatcount = 0;
                onupload=0;
                checkfile(file);
                //检查文件是否已经存在,并启动上传
                function checkfile( file) {
                    dommsg.text("正在检查文件..")
                    var checkreader = new FileReader();
                    var blob = file.slice(0,1024); //读取开始位置和结束位置的文件
                    checkreader.onload=function (){
                        var result = checkreader.result; //本次读取的数据
                        var fdjson={};
                        fdjson.checkdata=result;
                        fdjson.requesttype="chekcfile";
                        fdjson.filename= filename;
                        fdjson.size= file.size;
                        fdjson.location=window.location.pathname.replace("/jamupload.html","");
                        console.log(fdjson)

                        var xhr = new XMLHttpRequest();

                        xhr.open('post', '/jamfileupload', true);

                        xhr.onreadystatechange = function(res) {
                            if(xhr.readyState === 4 && xhr.status === 200) {
                                console.log(xhr.responseText,typeof xhr.responseText)
                                var jsonobj = JSON.parse(xhr.responseText); //可以将json字符串转换成json对象  //JSON.stringify(jsonobj); //可以将json对象转换成json对符串
                                dommsg.text("准备上传...")
                                console.log("checkrespon:",jsonobj.flag,jsonobj.startindex)
                                console.log("继续上传的位置:" + jsonobj.startindex);
                                startTime=new Date();
                                switch(jsonobj.flag) {

                                    case "0"://从头
                                        doUpload(file, 0);

                                        break;

                                    case "1"://续传

                                        doUpload(file, parseInt(jsonobj.startindex));

                                        break;

                                    case "2"://已经存在相同文件,秒传

                                        secondUpload(file);

                                        break;
                                    case "3"://文件名冲突,重命名
                                        console.log("文件名冲突!")
                                        filename=jsonobj.newName
                                        doUpload(file, 0);

                                        break;

                                }

                                repeatcount = 0;

                            } else if(xhr.readyState === 4 && xhr.status === 500) {

                                dommsg.text("中断重试中!")
                                setTimeout(function() {

                                    if(repeatcount < 3) {

                                        checkfile( file);

                                    }

                                    repeatcount++;

                                }, 3000);

                            }

                        }

                        //开始发送

                        xhr.send(JSON.stringify(fdjson));
                        }
                    checkreader.readAsDataURL(blob); //读取切割好的文件块

                }



                //实现秒传功能

                function secondUpload(file)
                {


                    domtime.text("文件完全相同,不上传");

                    //显示结果进度

                    var percent =100;

                    dommsg.text("成功!");

                    file["success"]="y";

                    domprogress.val(percent);

                    var total = file.size;

                    if (total > 1024 * 1024 * 1024) {

                        dompercentmb.text((total / 1024 / 1024 / 1024).toFixed(2) + "GB/" + (total / 1024 / 1024 / 1024).toFixed(2) + "GB");

                    } else if (total > 1024 * 1024) {

                        dompercentmb.text((total / 1024 / 1024).toFixed(2) + "MB/" + (total / 1024 / 1024).toFixed(2) + "MB");

                    } else if (total > 1024 && total < 1024 * 1024) {

                        dompercentmb.text((total / 1024).toFixed(2) + "KB/" + (total / 1024).toFixed(2) + "KB");

                    } else {

                        dompercentmb.text((total).toFixed(2) + "B/" + (total).toFixed(2) + "B");

                    }

                }

          //上传文件

                function doUpload(file,startindex) {

                    var dtime=new Date();

                    var reader = new FileReader();//新建一个读文件的对象

                    var step = 1024 * 1024*2; //每次读取文件大小  1MB

                    var cuLoaded = startindex; //当前已经读取总数

                    var total = file.size;//文件的总大小

                    //读取一段成功

                    reader.onload = function (e) {

                        if (onupload===1){//1是暂停
                            dommsg.text("暂停中")
                            throw new Error("暂停!")
                        }else if (onupload===2){//2是终止
                            dommsg.text("已取消!");
                            dompercentmb.text("已停止!")
                            stopsend();
                            throw new Error("中止!")
                        }

                        //处理读取的结果

                        var result = reader.result; //本次读取的数据

                        var loadedlen = e.loaded; //本次读取的数据长度
                        // console.log("result",result)
                        uploadFile(result, cuLoaded, loadedlen,function () { //将分段数据上传到服务器,传入回调函数

                            cuLoaded += loadedlen; //如果没有读完，继续

                            var timerange = (new Date().getTime() - startTime.getTime()) / 1000;

                            if (total > 1024 * 1024 * 1024) {

                                dompercentmb.text((cuLoaded / 1024 / 1024 / 1024).toFixed(2) + "GB/" + (total / 1024 / 1024 / 1024).toFixed(2) + "GB");

                            } else if (total > 1024 * 1024) {

                                dompercentmb.text((cuLoaded / 1024 / 1024).toFixed(2) + "MB/" + (total / 1024 / 1024).toFixed(2) + "MB");

                            } else if (total > 1024 && total < 1024 * 1024) {

                                dompercentmb.text((cuLoaded / 1024).toFixed(2) + "KB/" + (total / 1024).toFixed(2) + "KB");

                            } else {

                                dompercentmb.text((cuLoaded).toFixed(2) + "B/" + (total).toFixed(2) + "B");

                            }

                            rate=(loadedlen/1024/(new Date().getTime()-dtime.getTime())*1000).toFixed(2);
                            lefttime=(total-cuLoaded)/(rate*1024)//s
                            let lt = "";
                            if( lefttime>59) {
                                lt=(lefttime/60).toFixed(0)+"min"+(lefttime%60).toFixed(0)+"s"
                            }else if (lefttime>60*60){
                                lt=(lefttime/3600).toFixed(0)+"h"+((lefttime%3600)/60).toFixed(0)+"min"
                            }else{
                                lt=lefttime.toFixed(0)+"s"
                            }

                            domtime.text(rate+"KB/s  预计剩余:"+lt);
                            dtime=new Date();

                            if (cuLoaded < total) {

                                readBlob(cuLoaded);

                            } else {

                                console.log('总共用时：' + timerange);

                                cuLoaded = total;

                                sendfinish(); //告知服务器上传完毕

                                domtime.text("上传完成,用时" + timerange + "秒");

                            }

                            //显示结果进度

                            var percent = (cuLoaded/total) * 100;

                            dommsg.text("上传中:"+percent.toFixed(2) + "%");

                            domprogress.val(percent);

                        });

                    }
                    var n=0;
                    function stopsend() {

                        var fdjson={};
                        fdjson.requesttype="stopupload";
                        fdjson.filename= filename;
                        fdjson.totalsize= file.size;
                        fdjson.location=window.location.pathname.replace("/jamupload.html","");
                        console.log("stop:",fdjson)

                        var xhr = new XMLHttpRequest();

                        xhr.open('post', '/jamfileupload', true);

                        xhr.onreadystatechange = function () {
                            if (xhr.readyState === 4 && xhr.status === 200) {
                                dommsg.text("已取消!");
                            } else if (xhr.readyState === 4 && xhr.status === 500) {
                                console.log("取消出错")
                                dommsg.text("取消出错!");
                                // alert("出现错误")

                                 setTimeout(function() {

                                    if(n < 3) {

                                        stopsend();

                                    }

                                    n++;

                                }, 3000);

                            }

                        }

                        //发送

                        xhr.send(JSON.stringify(fdjson));

                }

                    function sendfinish() {

                        var fdjson={};
                        fdjson.requesttype="finishupload";
                        fdjson.filename= filename;
                        fdjson.totalsize= file.size;
                        fdjson.location=window.location.pathname.replace("/jamupload.html","");
                        console.log("finish:",fdjson)

                        var xhr = new XMLHttpRequest();

                        xhr.open('post', '/jamfileupload', true);

                        xhr.onreadystatechange = function () {
                            if (xhr.readyState === 4 && xhr.status === 200) {
                                dommsg.text("成功!");
                                file["success"]="y";
                                if (fn) {

                                    fn(); //如果上传成功,继续上传下一个文件

                                }


                            } else if (xhr.readyState === 4 && xhr.status === 500) {
                                console.log("出现错误")
                                dommsg.text("出现错误!");
                                // alert("出现错误")
                                var repeatcount=0;
                                 setTimeout(function() {

                                    if(repeatcount < 3) {

                                        checkfile( file);

                                    }

                                    repeatcount++;

                                }, 3000);

                            }

                        }

                        //发送

                        xhr.send(JSON.stringify(fdjson));

                    }

                    var m = 0;

                    //关键代码上传到服务器

                    function uploadFile(result, startIndex, loadedlen,onSuccess) {

                        var datajs={};
                        datajs.data=result;
                        datajs.requesttype="uploaddata";
                        datajs.filename= filename;
                        datajs.size= loadedlen;
                        datajs.location=window.location.pathname.replace("/jamupload.html","");
                        datajs.startindex=startIndex;

                        var xhr = new XMLHttpRequest();

                        xhr.open('post', '/jamfileupload', true);

                        xhr.onreadystatechange = function () {

                            if (xhr.readyState === 4 && xhr.status === 200) {

                                m = 0;

                                if (onSuccess)

                                    onSuccess();

                            } else if (xhr.status === 500) {
                                console.log("错误")
                                setTimeout(function () {

                                    if (m < 3) {

                                        containue();

                                        m++;

                                    }

                                }, 1000);

                            }

                        }

                        //开始发送

                        xhr.send(JSON.stringify(datajs));

                    }



                    //指定开始位置，分块读取文件

                    function readBlob(start) {

                        //指定开始位置和结束位置读取文件

                        var blob = file.slice(start, start + step); //读取开始位置和结束位置的文件

                        reader.readAsDataURL(blob); //读取切割好的文件块

                    }

                    //继续

                    function containue() {

                        readBlob(cuLoaded);

                    }

                    readBlob(cuLoaded);

                }





            }

      document.onchange=function (){
          console.log("change")
          footerchange();
      }
      function footerchange(){
           var _wh = $(window).height();
          var _bh = $(document.body).height();
          if (_bh+50 < _wh) {
              console.log("1111")
            $("#footer").css({
              position: "fixed",
              bottom: "0",
              left: "0",
            })
          } else {
              console.log('2222')
            $("#footer").css({
              position: "static",
              bottom: "auto",
              left: "auto",
            })
          }
      }
      footerchange();

</script>

  </body>

</html>

